import {
  collectInterfaceInfoUsingPost,
  likeInterfaceInfoUsingPost,
  listInterfaceInfoByPageUsingGet
} from '@/services/openAPI-backend/interfaceInfoController';
import { LikeOutlined, MessageOutlined, StarOutlined,SmileOutlined } from '@ant-design/icons';
import {type ActionType, PageContainer} from '@ant-design/pro-components';
import {Avatar, Button, Card, Col, Drawer, List, Row, Space, message, notification} from 'antd';
import CommentModal from '@/pages/api_interfaceinfo/components/CommentModal';
import React, {useEffect, useRef, useState} from 'react';
import {getCommentByInterfaceIdUsingGet} from "@/services/openAPI-backend/commentController";
interface DescriptionItemProps {
  title: string;
  content: React.ReactNode;
}
import type { NotificationArgsProps } from 'antd';
import {keyframes} from "antd-style";
type NotificationPlacement = NotificationArgsProps['placement'];
const IconText = ({ icon, text }: { icon: React.FC; text: string }) => (
  <Space>
    {React.createElement(icon)}
    {text}
  </Space>
);

/**
 * 每个用户都能看到的接口表格
 * @param param0
 * @returns
 */

const Welcome: React.FC = () => {
    const fadeIn = keyframes`
        0% {
            clip-path: inset(0 0 100% 0); /* 初始时，元素被裁剪仅显示左侧边缘 */
        }
        100% {
            clip-path: inset(0 0 0 0); /* 完全展开，无裁剪 */
        }
    `;
  const actionRef = useRef<ActionType>();
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState<API.InterfaceInfo[]>();
  const [total, setTotal] = useState<number>();
  const [DrawerData, setDrawerData] = useState<API.InterfaceInfo>();
  const [commentList, setCommentList] = useState<API.Comment[]>();
  const [Draweropen, setDrawerOpen] = useState(false);
  // const user = sessionStorage.getItem('loginUser');
  const [commentModalOpen, handleCommentModalOpen] = useState<boolean>(false);


  const showDrawer = (values: API.InterfaceInfo) => {
    setDrawerOpen(true);
    setDrawerData(values);
  };
  const getComment = async (id) => {
    try{
      const res = await getCommentByInterfaceIdUsingGet({
        interfaceInfoId:id,
      });
      setCommentList(res.data);
    }catch (e){
      console.log(e);
    }
  }
  const DescriptionItem = ({ title, content }: DescriptionItemProps) => (
    <div
      className="site-description-item-profile-wrapper"
      style={{
        display: 'flex',
        marginBottom: 12,
        marginTop: 5,
        fontSize: 15,
      }}
    >
      {title}:
      <p
        style={{
          color: '#ad2102',
          marginLeft: 8,
          fontSize: 15,
        }}
      >
        {' '}
        {content}
      </p>
    </div>
  );
  const onClose = () => {
    loadData();
    setDrawerOpen(false);
  };
  const ondrawClose = () => {
    loadData();
    handleCommentModalOpen(false);
  };
    const fadeAndScaleIn = keyframes` 
        from {
            opacity: 0;
            transform: translateX(20px);
        }
        to {
            opacity: 1;
            transform: translateX(0);
        }

    `;
  const onGood = async (infoID : number) => {
    try{
     const res = await likeInterfaceInfoUsingPost({
        interfaceInfoId: infoID,
      });
      loadData();
    }catch(error){
        message.error('点赞失败');
    }

  };
  /**
   * 获取url到剪切板
   */
  const  tryLegacyCopy=(url)=> {
    // 创建一个隐藏的textarea元素
    const textarea = document.createElement('textarea');
    textarea.value = url;
    textarea.style.position = 'fixed'; // 防止影响页面布局
    textarea.style.top = 0;
    textarea.style.left = 0;
    textarea.style.width = '1px';
    textarea.style.height = '1px';
    textarea.style.padding = 0;
    textarea.style.border = 'none';
    textarea.style.outline = 'none';
    textarea.style.boxShadow = 'none';
    textarea.style.background = 'transparent';

    document.body.appendChild(textarea);
    textarea.select();

    // 尝试复制
    const copied = document.execCommand('copy');

    // 清理
    document.body.removeChild(textarea);

    if (copied) {
      message.success('url已复制到剪切板');
    } else {
      console.error('Failed to copy URL to clipboard with the legacy method');
      // 可以进一步处理错误情况
    }
  }

  const copyUrl = (url: string) => {
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard
        .writeText(url)
        .then(() => {
          message.success('url已复制到剪切板');
        })
        .catch((error) => {
          console.error('Error copying URL to clipboard:', error);
          // 处理错误，例如显示警告信息
        });
    }else{
      tryLegacyCopy(url);
    }
  };
  const onCollect = async (id) => {
    try {
    const res =  await collectInterfaceInfoUsingPost({
        interfaceInfoId: id,
      })
      loadData();
      notification.info({
        message:"系统提示",
        description:res.data,
        placement:'topRight',
        duration:2,
      });
    if(res.data==='收藏成功') {
      setIsCollect[id](true);

    }
      else {
      setIsCollect[id](false)
    }

    }catch (e){
      message.error(e);
    }
  };
  const loadData = async (current: number = 1, pageSize: number = 10) => {
    setLoading(true);
    try {
      const res = await listInterfaceInfoByPageUsingGet({
        current,
        pageSize,
      });
      setList(res?.data?.records ?? []);
      setTotal(res.data?.total ?? 0);
    } catch (error) {
      message.error("加载失败，请重试'");
    }
    setLoading(false);
  };
  useEffect(() => {
    loadData();
  }, []);

  return (
    <PageContainer>
      <List
        className="API-list"
        loading={loading}
        itemLayout="vertical"
        dataSource={list}
        size="large"
        renderItem={(item, index) => {
          const apilink = `/interface_info/${item.id}`;
          return (
              <Card
                  key = {index}
                  hoverable={true}
                  style={{
                      borderRadius: '20px',
                      backgroundColor: '#ffffff', // 给卡片一个干净的白色背景
                      boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)', // 添加微妙的阴影效果，提升层次感
                      transition: 'all 0.3s ease', // 平滑的过渡效果，包括但不限于变换和opacity
                      marginBottom: '5px', // 增加底部外边距，让卡片之间有更好的间距
                      animation: `${fadeIn} 0.5s cubic-bezier(0.4, 0, 0.2, 1) both`,
                      animationDelay: `${index * 0.1}s`,
                  }}
              >
            <List.Item
              actions={[
                <Button style={{
                    transition: 'background-color 0.3s', // 添加背景色过渡
                }}
                        onMouseDown={(e) => e.currentTarget.style.backgroundColor = '#d4380d'}
                        onMouseUp={(e) => e.currentTarget.style.backgroundColor = ''}  size='middle' shape='round' type="text" key='Like' onClick={() => {onGood(item.id)}} >
                <LikeOutlined
                  key="list-vertical-like-o"
                  style={{
                    color: 'red',
                  }}

                /> <a style={{fontSize:'15px'}}>{item.likes}</a></Button>,
                <Button style={{
                    transition: 'background-color 0.3s', // 添加背景色过渡
                }}
                        onMouseDown={(e) => e.currentTarget.style.backgroundColor = '#fadb14'}
                        onMouseUp={(e) => e.currentTarget.style.backgroundColor = ''}  size='middle' shape='round' type="text" key='love' onClick={() => {onCollect(item.id)}} >
                  <StarOutlined
                  key="list-vertical-like-o"
                  style={{
                    color:'#d4b106',
                  }}
                /> <a style={{fontSize:'15px'}}>{item.collections}</a></Button>,
                <Button style={{
                    transition: 'background-color 0.3s', // 添加背景色过渡
                }}
                        onMouseDown={(e) => e.currentTarget.style.backgroundColor = '#c41d7f'} // 按下时改变颜色
                        onMouseUp={(e) => e.currentTarget.style.backgroundColor = ''}  size='middle' shape='round' type="text" key='Comment' onClick={() => {
                  sessionStorage.setItem('CinterfaceInfoId',item.id);
                  getComment(item.id);
                  handleCommentModalOpen(true);}}><IconText style={{fontSize:'15px'}} icon={MessageOutlined} text={item.comments} key="list-vertical-message" /></Button>,
                <a

                  style={{
                    display: 'flex',
                    textAlign: 'right',
                    fontSize: '15px',
                  }}
                  key={item.id}
                  onClick={() => {
                    showDrawer(item);
                  }}
                >
                  查看
                </a>,
                <a
                  style={{
                    display: 'flex',
                    textAlign: 'right',
                    fontSize: '15px',
                  }}
                  key={item.id}
                  href={apilink}
                >
                  测试
                </a>,
                <a
                  style={{
                    display: 'flex',
                    textAlign: 'right',
                    fontSize: '15px',
                  }}
                  onClick={() => copyUrl(item.url)}
                  key="list-loadmore-more"
                >
                  复制url
                </a>,<a
                  style={{
                    display: 'flex',
                    textAlign: 'right',
                    fontSize: '15px',
                  }}
                  key={item.id}
                  onClick={()=>{notification.info({
                 message:"当前版本v1",
                 description:"更新后将触发版本管理",
                 placement:"topRight",
                  icon: <SmileOutlined style={{ color: '#108ee9' }} />,
})}}
                >
                  版本
                </a>,
                <CommentModal key="1" isOpen={commentModalOpen} onClose={ondrawClose} data={commentList}/>
              ]}
            >
              <List.Item.Meta
                avatar={<Avatar src={`https://api.dicebear.com/7.x/miniavs/svg?seed=${index}`} />}
                title={
                  <a
                    style={{
                      fontSize: 16,
                    }}
                    href={apilink}
                  >
                    {item.name}
                  </a>
                }
                description={item.description}
              />
            </List.Item>
</Card>
          );
        }}
        pagination={{
          showTotal(total: number) {
            return '总数' + total;
          },
          pageSize: 5,
          total,
          onChange(page, pageSize) {
            loadData(page, pageSize);
          },
        }}
      />
      <Drawer
        width={720}
        styles={{fontSize:'18px'}}
        placement="right"
        closable={false}
        onClose={onClose}
        open={Draweropen}
        extra={<Space></Space>}
        size="default"
        keyboard={true}
      >
        <Card
          title={<p style={{fontSize: '24px',fontWeight: 'bold',marginTop: 20}}>接口详细信息</p>}
          style={{
            width: 580,
            fontSize: 55,
            marginBottom: 24,
            marginLeft: 5,
            borderRadius: 10,
            border: 0,
            justifyContent: 'space-between',
          }}
        >
          <Row>
            <Col span={12}>
              <DescriptionItem title="ID" content={DrawerData?.id}/>
            </Col>
            <Col span={12}>
              <DescriptionItem title="Name" content={DrawerData?.name} />
            </Col>
          </Row>
          <Row >
              <Col span={24}>
              <DescriptionItem title="描述" content={DrawerData?.description} style={{ whiteSpace: 'pre-wrap' }} />
            </Col>
          </Row>
          <Row>
            <Col>
              <DescriptionItem title="接口URL" content={DrawerData?.url} />
            </Col>
          </Row>
          <Row>
            <Col span={500}>
             <p>请求头：<a style={{color:'#ad2102',fontSize:"15px"}}>{DrawerData?.requestHeader}</a></p>
              
            </Col>
          </Row>
          <Row>
            <Col>
              <DescriptionItem title="响应头" content={DrawerData?.responseHeader} />
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <DescriptionItem
                title="接口状态"
                content={DrawerData?.status == 1 ? '已发布' : '已下线'}
              />
            </Col>
            <Col>
              <DescriptionItem title="请求方式" content={DrawerData?.method} />
            </Col>
          </Row>
          <Row>
            <Col>
              <DescriptionItem title="创建时间" content={DrawerData?.createTime} />
            </Col>
          </Row>
          <Row>
            <Col>
              <DescriptionItem title="更新时间" content={DrawerData?.updateTime} />
            </Col>
          </Row>
          <Row>
            <Col>
              <DescriptionItem title="请求参数" content={DrawerData?.requestParams} />
            </Col>
          </Row>
        </Card>
        <Space
          style={{
            display: 'flex',
            justifyContent: 'flex-end',
            alignItems: 'flex-end',
          }}
        >
          <Button onClick={onClose}>Cancel</Button>
          <Button type="primary" onClick={onClose}>
            OK
          </Button>
        </Space>
      </Drawer>
    </PageContainer>
  );
};

export default Welcome;
